<?php

namespace app\api\controller;
//导入基类
use app\common\model\ApplicationRedeem;
use app\common\model\Coupon;
use app\common\model\IntegralLog;
use app\common\model\Message;
use app\common\model\Reward;
use app\common\model\UserCoupon;
use app\common\model\Money;
use app\common\model\Redeem;
use app\common\model\UserCoupon as user_couponModel;
use app\common\model\User as userModel;
use app\common\model\Goods;
use app\common\model\Notice;
use app\common\model\CheckIn;
use app\common\model\IntegralLottery;
use app\common\validate\User as userValidate;
use think\Controller;
use think\facade\Cache;
use think\Db;
use app\common\model\Goods as goodsModel;
use think\Request;
use app\common\model\IntegralLog as integralLoglModel;
use app\common\model\WalletLog;
class User extends Controller
{
    //个人中心首页
    public function index()
    {
        $data = array('code'=>1,'msg'=>'数据异常');
        $userid = session('userid');
        $info = userModel::where('id',$userid)->field('id,nickname,head_img,user_level')->find();
        $level = ['普通会员','VIP'];
        $info['level'] = $level[$info['user_level']];
        $data = [
            'code'=>0,
            'msg'=>'获取成功',
            'info'=>$info
        ];
        return json($data);
    }
    //我的钱包
    public function my_wallet(){
        $data = array('code'=>1,'msg'=>'数据异常');
        $userid = session('userid');
        $wallet = Money::where('userid',$userid)->value('balance');
        $data = [
            'code'=>0,
            'msg'=>'获取成功',
            'wallet'=>$wallet
        ];
        return json($data);
    }
    //我的积分
    public function my_integral(){
        $data = array('code'=>1,'msg'=>'数据异常');
        $userid = session('userid');
        $integral = Money::where('userid',$userid)->value('integral');
        //积分排行榜
        $ranking_list = Money::alias('m')->Join('langjin_user u','m.userid = u.id')->field('m.integral,u.nickname,u.head_img,u.id')->order('m.integral desc')->limit(20)->select();
        $data = [
            'code'=>0,
            'msg'=>'获取成功',
            'info'=>[
                'integral' =>$integral,
                'ranking_list' =>$ranking_list,
            ]
        ];
        return json($data);
    }
    //积分兑换列表
    public function redeem_list(){
        $data = array('code'=>1,'msg'=>'数据异常');
        $info = Redeem::order('id desc')->select();
        $data = [
            'code'=>0,
            'msg'=>'获取成功',
            'info'=>$info
        ];
        return json($data);
    }
    //积分兑换申请
    public function application_duihuan(){
        $data = array('code'=>1,'msg'=>'数据异常');
        if(request()->isPost()) {
            $redeem_id = $this->request->param('id');
            $info = Redeem::where('id',$redeem_id)->find();
            if(!$info || !$redeem_id){
                return json($data);
            }
            //判断用户积分是否足够
            $userid = session('userid');
            $integral = Money::where('userid',$userid)->value('integral');
            //如果余额不足
            if(bccomp($integral, $info['integral'], 2) <0){
                $data = array('code'=>1,'msg'=>'积分不足');
                return json($data);
            }else{
                // 启动事务
                Db::startTrans();
                try {
                //如果足够的话就加入申请列表并先扣除积分
                $res = [
                    'userid'=>$userid,
                    'balance'=>$info['balance'],
                    'integral'=>$info['integral'],
                    'status'=>0,
                    'create_time'=>time(),

                ];
                $result = ApplicationRedeem::create($res);
                if($result){
                    //如果申请成功的话扣除积分 添加积分记录
                    $res1 = [
                        //添加积分记录
                            'userid' => $userid,
                            'num' => $info['integral'],
                            'type' => 1,//余额兑换扣除
                        ];
                    $result1 = IntegralLog::create($res1);
                    if($result1){
                        Money::where('userid', $userid)->setDec('integral',$info['integral']);
                        $data = array('code'=>0,'msg'=>'申请兑换成功');
                    }
                }
                    // 提交事务
                    Db::commit();
                    return json($data);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return json($data);
                }
            }
        }
        return json($data);
    }
    //我的优惠券
    /**
    *type 0未使用 1 已使用  2已过期
     **/
    public function my_coupon(){
        $data = array('code'=>1,'msg'=>'数据异常');
        $userid = session('userid');
        UserCoupon::alias('u')->join('langjin_coupon c','c.id = u.coupon_id')->where('u.userid',$userid)->where('c.expired_time','<',time())->update(['u.status'=>2]);
        $param = $this->request->param();
        $type =$this->request->param('type')?$this->request->param('type'):0;
        $start = 0;
        $limit = 10;
        if (!empty($param['length']) && !empty($param['start'])) {
            $start = ($param['start'] - 1) * $param['length'];
            $limit = $param['length'];
        }
        $coupon_list = UserCoupon::alias('u')->Join('langjin_coupon c','u.coupon_id = c.id')->Join('langjin_coupon_cate ca','c.cat_id = ca.id')->where(['u.userid'=>$userid,'u.status'=>$type])->field('u.id,c.cat_id,c.amount,c.full_amount,ca.coupon_name')->limit($start, $limit)->select();
        $count = UserCoupon::alias('u')->Join('langjin_coupon c','u.coupon_id = c.id')->Join('langjin_coupon_cate ca','c.cat_id = ca.id')->where(['u.userid'=>$userid,'u.status'=>$type])->count();
       /* foreach($coupon_list as $key=>$value){
            $coupon_cat = Coupon::where('id',$value['coupon_id'])->value('cat_id');
            $coupon_list[$key]['coupon_cat'] = $coupon_cat;
        }*/
        $data = [
            'code'=>0,
            'msg'=>'获取成功',
            'info'=>$coupon_list,
            'count'=>$count,
        ];
        return json($data);
    }
    //优惠券列表
    public function coupon(){
        $data = array('code'=>1,'msg'=>'数据异常');
        $param = $this->request->param();
        $start = 0;
        $limit = 10;
        if (!empty($param['length']) && !empty($param['start'])) {
            $start = ($param['start'] - 1) * $param['length'];
            $limit = $param['length'];
        }
        Coupon::where('expired_time','<',time())->update(['status'=>1]);
        $coupon_list = Coupon::alias('c')->Join('langjin_coupon_cate ca','c.cat_id = ca.id')->where(['c.status'=>0])->field('c.id,c.cat_id,c.amount,c.full_amount')->limit($start, $limit)->select();
        $count = Coupon::alias('c')->Join('langjin_coupon_cate ca','c.cat_id = ca.id')->where(['c.status'=>0])->count();
        $data = [
            'code'=>0,
            'msg'=>'获取成功',
            'info'=>$coupon_list,
            'count'=>$count,
        ];
        return json($data);
    }
    //领取优惠券
    public function receive_coupon(){
        $data = array('code'=>1,'msg'=>'数据异常');
        $userid = session('userid');
        $param = $this->request->param();
        if(empty($param['id'])){
            return json($data);
        }
        $res = Coupon::where('id',$param['id'])->find();
        if(empty($res)){
            return json($data);
        }
        $result = UserCoupon::where(['userid'=>$userid,'coupon_id'=>$param['id']])->count();
        if($result){
            $data = array('code'=>1,'msg'=>'您已经领取该优惠券');
            return json($data);
        }
        //查看优惠券是否禁用
        if($res['status'] == 1){
            $data = array('code'=>1,'msg'=>'该优惠券异常');
            return json($data);
        }
        //查看数量是否还有
        if($res['number'] <=0){
            $data = array('code'=>1,'msg'=>'该优惠券已领完');
            return json($data);
        }
        //查看优惠券是否已过期
        if($res['expired_time'] <time()){
            $data = array('code'=>1,'msg'=>'该优惠券已过期');
            return json($data);
        }
        //领取优惠券
        $info = [
            'userid'=>$userid,
            'coupon_id'=>$res['id'],
            'create_time'=>time(),
            'status'=>0,
            'expired_time'=>$res['expired_time'],
        ];
        $res1 = UserCoupon::create($info);
        //优惠券数量减1
        $res2 = Coupon::where('id',$res['id'])->setDec('number',1);
        if($res1 && $res2){
            $data = array('code'=>0,'msg'=>'领取成功');
            return json($data);
        }
        return json($data);
    }
    //我的海报
    public function my_poster(){
        $param = $this->request->param();
        $start = 0;
        $limit = 10;
        if (!empty($param['length']) && !empty($param['start'])) {
            $start = ($param['start'] - 1) * $param['length'];
            $limit = $param['length'];
        }
        $goods_list =Goods::order('id desc')->limit($start,$limit)->select();
        $poster_count = Goods::count();
        $poster = array();
        //print_r($goods_list);exit;
        foreach($goods_list as $key=>$value){
            $poster[] = $value['poster'];
        }
        $data = array('code'=>0,'msg'=>'获取成功','poster_img'=>$poster,'count'=>$poster_count);
        return json($data);
    }
    //旅游攻略
    public  function my_team(){
        $info = Notice::where('id',2)->value('content');
        $data  = [
            'code'=>0,
            'msg'=>'请求成功',
            'info'=>$info,
        ];
        return json($data);
    }
    //我的邀请
    public function my_invite(){
        $userid = session('userid');
        $param = $this->request->param();
        $start = 0;
        $limit = 10;
        if (!empty($param['length']) && !empty($param['start'])) {
            $start = ($param['start'] - 1) * $param['length'];
            $limit = $param['length'];
        }
        $info = userModel::where('parent_id',$userid)->field('id,nickname,create_time')->order('id desc')->limit($start,$limit)->select();
        $count = userModel::where('parent_id',$userid)->count();
        $data = array('code'=>0,'msg'=>'获取成功','info'=>$info,'count'=>$count);
        return json($data);
    }
    //签到页面
    public function check_html(){
        $userid = session('userid');
        $start_time = strtotime(date('Y-m-d',time()));
        $end_time = $start_time+86400;
        $info = CheckIn::where('userid',$userid)->where('create_time','>=',$start_time)->where('create_time','<',$end_time)->count();
        if($info){
            $status = 1;
        }else{
            $status = 0;
        }
        //积分签到获得积分
        $integral_num = Reward::where('field','check_in')->value('tip');
        //echo Reward::getLastSql();exit;
        $data = array('code'=>0,'msg'=>'获取成功','status'=>$status,'integral_num'=>$integral_num);
        return json($data);
    }
    //签到提交
    public function check_sub(){
        $data = array('code'=>1,'msg'=>'数据异常');
        if(request()->isPost()) {
            $userid = session('userid');
            $start_time = strtotime(date('Y-m-d',time()));
            $end_time = $start_time+86400;
            $info = CheckIn::where('userid',$userid)->where('create_time','>=',$start_time)->where('create_time','<',$end_time)->count();
            if($info){
                $data = array('code'=>1,'msg'=>'您今天已签到过了');
            }else{
                //积分签到获得积分
                $integral_num = Reward::where('field','check_in')->value('tip');
                //添加积分记录，增加积分
                $data1 = [
                    'userid' => $userid,
                    'num' => $integral_num,
                    'type' => 2,//签到获得
                ];
                $result = integralLoglModel::create($data1);
                //添加签到记录
                $data2 = [
                    'userid' => $userid,
                    'money' => $integral_num,
                    'create_time' => time(),
                    ];
                $result1 = CheckIn::create($data2);
                if($result && $result1){
                    $res = Money::where('userid', $userid)->setInc('integral',$integral_num);
                    if($res){
                        $data = array('code'=>0,'msg'=>'签到成功');
                        return json($data);
                    }
                }
            }
        }
        return json($data);
    }
    //积分抽奖
    public function integral_lottery(){
        $data = array('code'=>1,'msg'=>'数据异常');
        if(request()->isPost()) {
            $integral_num =$this->request->param('integral_num')?$this->request->param('integral_num'):0;
            if(!$integral_num){
                return json($data);
            }
            $userid = session('userid');
            $start_time = strtotime(date('Y-m-d',time()));
            $end_time = $start_time+86400;
            $info = IntegralLottery::where('userid',$userid)->where('create_time','>=',$start_time)->where('create_time','<',$end_time)->count();
            if($info) {
                $data = array('code' => 1, 'msg' => '您今天已经参与过抽奖');
            }else{
                //添加积分记录，增加积分
                //添加积分记录，增加积分
                $data1 = [
                    'userid' => $userid,
                    'num' => $integral_num,
                    'type' => 4,//签到获得
                ];
                $result = integralLoglModel::create($data1);
                //添加抽奖记录
                $data2 = [
                    'userid' => $userid,
                    'integral' => $integral_num,
                    'create_time' => time(),
                ];
                $result1 = IntegralLottery::create($data2);
                if($result && $result1){
                    $res = Money::where('userid', $userid)->setInc('integral',$integral_num);
                    if($res){
                        $data = array('code'=>0,'msg'=>'抽奖成功');
                        return json($data);
                    }
                }
            }
        }
        return json($data);
    }
    //提交留言
    public function sub_message(){
        $data = array('code'=>1,'msg'=>'数据异常');
        if(request()->isPost()) {
            $userid = session('userid');
            $content =$this->request->param('content');
            if(!$content){
                $data = array('code'=>1,'msg'=>'留言不能为空');
            }else{
                $info = [
                    'userid'=>$userid,
                    'content'=>$content,
                    'create_time'=>time(),
                ];
                $res = Message::create($info);
                if($res){
                    $data = array('code'=>0,'msg'=>'提交成功');
                }
            }
            return json($data);
        }
        return json($data);
    }
    //信息修改
    public function personal_information(){
        $userid = session('userid');
        $data = array('code'=>1,'msg'=>'数据异常');
        if(request()->isPost()) {
            $res['nickname'] =$this->request->param('nickname');
            $res['mobile']  =$this->request->param('mobile');

            $validate = new \app\common\validate\User();
            if (!$validate->check($res)) {
                $data = array('code'=>1,'msg'=>$validate->getError());
                return json($data);
            }
            $result = userModel::where('id',$userid)->update(['nickname'=>$res['nickname'],'mobile'=>$res['mobile']]);
            if($result){
                $data = array('code'=>0,'msg'=>'修改成功');
            }
            return json($data);
        }
        $info = userModel::where('id',$userid)->field('nickname,mobile')->find();
        $data = array('code'=>0,'msg'=>'获取成功','info'=>$info);
        return json($data);
    }
}